//! 管理用户数据相关

import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { loginAPI } from '@/apis/user'
import { mergeCartAPI } from '@/apis/cart'
import { useCartStore } from '@/stores/cartStore'



export const useUserStore = defineStore('user', () => {
    //!配置位于main.js
    //!目的：保持token不丢失，保持登录状态
    //!最终效果：操作state时会自动把用户数据在本地的localStorage也存一份，刷新的时候会从localStorage中先取
    //!pinia-plugin-persistedstate
    //!适用于Pinia的持久化存储插件
    //! npm i pinia-plugin-persistedstate
    const userInfo = ref({})
    // const token = ref('')
    const cartStore = useCartStore()
    const getUserInfo = async ({ account, password }) => {
        let res = await loginAPI({ account, password })
        //!1.成功后提示用户，跳转首页
        if (res.code == 1) {
            userInfo.value = res.result
            // token.value = localStorage.setItem('TOKEN', JSON.stringify(res.result))
        }
        //!2.在登录时候执行合并购物车的操作
        await mergeCartAPI(cartStore.cartList.map(item => {
            return {
                skuId: item.skuId,
                selected: item.selected,
                count: item.count
            }
        }))
        //!3.获取最新链表
        cartStore.getCart()
    }
    //退出时候清除用户信息
    const clearUserInfo = () => {
        userInfo.value = {}
    }
    return { userInfo, getUserInfo, clearUserInfo }
}, {
    persist: true
})
